import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

class Image {
    public String name;
    public String url;
}

@WebServlet("/Image")
public class OnlineImageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        // 1. 扫描指定路径 /webapp/image 路径
        List<Image> images = loadImage();
        // 2. 构造到模板页面
        TemplateEngine engine = (TemplateEngine) getServletContext().getAttribute("engine");
        WebContext webContext = new WebContext(req,resp,getServletContext());
        webContext.setVariable("images",images);
        String html = engine.process("image",webContext);
        resp.getWriter().write(html);
    }

    private List<Image> loadImage() {
        List<Image> images = new ArrayList<>();
        // 首先得到 /webapp/image 的绝对路径
        ServletContext context = this.getServletContext();
        // 这里是将 webapp下的目录转换成一个绝对路径
        String path = context.getRealPath("/image");
        // 根据路径 看里面有哪些图片.
        File file = new File(path);
        File[] files = file.listFiles();
        for(File f:files){
            Image image = new Image();
            image.name = f.getName();
            image.url = "image/"+f.getName();
            images.add(image);
        }
        return images;
    }

}
